package com.szp.lagou.mq.rocketmq.task;

import com.szp.lagou.mq.rocketmq.constant.Constants;
import com.szp.lagou.mq.rocketmq.pojo.Order;
import com.szp.lagou.mq.rocketmq.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class UnpayedOrderTask implements ApplicationListener<ApplicationStartedEvent> {
    @Autowired
    OrderService orderService;

    @Value("${order.mq.message.ttl}")
    private String orderMqMessageTtl;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);


    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        executor.scheduleAtFixedRate(() -> {
                    List<Order> unPayOrders = orderService.getUnPayOrders(10);
                    for (Order order : unPayOrders) {
                        if (order.getStatus().equals("0")) {
                            Date createTime = order.getCreateTime();
                            Instant orderTimeInstant = createTime.toInstant();
                            Instant now = Instant.now();
                            if (Duration.between(orderTimeInstant, now).getSeconds() * 1000 > Long.parseLong(orderMqMessageTtl)) {
                                System.out.println("订单" + order.getId() + "过期未支付");
                                orderService.updateOrderStatusById(order.getId(), "2");
                                redisTemplate.opsForValue().increment(Constants.KILL_REDIS_KEY, 1);
                            }
                        }
                    }
                },
                10L, 5, TimeUnit.SECONDS);
    }
}
